"""
UI自动化API路由
"""

from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
import asyncio
import json

from ...core.database import get_db
from ...core.security import get_current_user
from ...models.user import User
from ...models.ui_automation import ExecutionStatus
from ...schemas.ui_automation import (
    UiAutomationScriptCreate, UiAutomationScriptUpdate, UiAutomationScript,
    UiAutomationScriptWithDetails, YamlGenerationRequest, YamlGenerationResponse,
    UiAutomationExecutionCreate, UiAutomationExecution, UiAutomationExecutionDetail,
    UiAutomationBatchCreate, UiAutomationBatch, UiAutomationBatchDetail,
    UiAutomationScriptListParams, UiAutomationExecutionListParams,
    UiAutomationListResponse, UiAutomationResponse
)
from ...models import ui_automation as ui_automation_models
from ...services.ui_automation_service import UiAutomationService
from ...services.ui_file_service import UiFileService

router = APIRouter()


# 脚本管理相关接口
@router.post("/scripts", response_model=UiAutomationResponse)
async def create_ui_automation_script(
    script_data: UiAutomationScriptCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建UI自动化脚本"""
    try:
        service = UiAutomationService(db)
        script_model = await service.create_script(script_data, current_user.id)
        # 转换为Pydantic schema
        script_schema = UiAutomationScript.from_orm(script_model)
        return UiAutomationResponse(
            success=True,
            message="脚本创建成功",
            data=script_schema
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/scripts", response_model=UiAutomationListResponse)
def get_ui_automation_scripts(
    page: int = 1,
    size: int = 20,
    search: Optional[str] = None,
    requirement_id: Optional[int] = None,
    status: Optional[str] = None,
    tags: Optional[str] = None,
    created_by: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取UI自动化脚本列表"""
    try:
        service = UiAutomationService(db)
        result = service.get_scripts(
            page=page,
            size=size,
            search=search,
            requirement_id=requirement_id,
            status=status,
            tags=tags,
            created_by=created_by
        )
        
        # 转换items中的SQLAlchemy模型为Pydantic schema
        script_schemas = [UiAutomationScript.from_orm(script) for script in result["items"]]
        result["items"] = script_schemas
        
        return UiAutomationListResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/scripts/{script_id}", response_model=UiAutomationResponse)
def get_ui_automation_script(
    script_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取UI自动化脚本详情"""
    service = UiAutomationService(db)
    script_model = service.get_script(script_id)
    if not script_model:
        raise HTTPException(status_code=404, detail="脚本不存在")
    
    # 转换为Pydantic schema
    script_schema = UiAutomationScript.from_orm(script_model)
    return UiAutomationResponse(
        success=True,
        message="获取成功",
        data=script_schema
    )


@router.put("/scripts/{script_id}", response_model=UiAutomationResponse)
async def update_ui_automation_script(
    script_id: int,
    script_data: UiAutomationScriptUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新UI自动化脚本"""
    try:
        service = UiAutomationService(db)
        script_model = await service.update_script(script_id, script_data)
        if not script_model:
            raise HTTPException(status_code=404, detail="脚本不存在")
        
        # 转换为Pydantic schema
        script_schema = UiAutomationScript.from_orm(script_model)
        return UiAutomationResponse(
            success=True,
            message="脚本更新成功",
            data=script_schema
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.delete("/scripts/{script_id}", response_model=UiAutomationResponse)
def delete_ui_automation_script(
    script_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除UI自动化脚本"""
    service = UiAutomationService(db)
    result = service.delete_script(script_id)
    if not result:
        raise HTTPException(status_code=404, detail="脚本不存在")
    
    return UiAutomationResponse(
        success=True,
        message="脚本删除成功"
    )


# YAML脚本生成相关接口
@router.post("/scripts/generate-yaml", response_model=UiAutomationResponse)
async def generate_yaml_script(
    request: YamlGenerationRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """基于需求生成YAML脚本"""
    try:
        service = UiAutomationService(db)
        result = await service.generate_yaml_from_requirement(request)
        return UiAutomationResponse(
            success=True,
            message="YAML脚本生成成功",
            data=result
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/scripts/validate-yaml", response_model=UiAutomationResponse)
def validate_yaml_script(
    yaml_content: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """验证YAML脚本格式"""
    try:
        service = UiAutomationService(db)
        result = service.validate_yaml_script(yaml_content)
        return UiAutomationResponse(
            success=result["valid"],
            message="验证完成" if result["valid"] else result["error"],
            data=result
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/scripts/{script_id}/execute", response_model=UiAutomationResponse)
async def execute_ui_automation_script(
    script_id: int,
    execution_options: dict = None,
    background_tasks: BackgroundTasks = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """启动UI自动化脚本执行（异步模式）"""
    try:
        service = UiAutomationService(db)
        
        # 验证脚本是否存在
        script = service.get_script(script_id)
        if not script:
            raise HTTPException(status_code=404, detail="脚本不存在")
        
        # 创建执行记录（不立即执行）
        execution = await service.create_execution_record(
            script_id, 
            execution_options or {}, 
            current_user.id
        )
        
        # 转换SQLAlchemy模型为Pydantic模式
        execution_schema = UiAutomationExecution.from_orm(execution)
        
        return UiAutomationResponse(
            success=True,
            message="脚本执行已创建，请使用stream端点获取实时输出",
            data={
                "execution_id": execution.id,
                "execution": execution_schema,
                "stream_url": f"/api/v1/ui-automation/executions/{execution.id}/stream"
            }
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


# 执行相关接口
@router.post("/executions", response_model=UiAutomationResponse)
async def create_ui_automation_execution(
    execution_data: UiAutomationExecutionCreate,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建并执行UI自动化脚本"""
    try:
        service = UiAutomationService(db)
        execution_model = await service.create_execution(execution_data, current_user.id)
        
        # 在后台执行脚本
        background_tasks.add_task(service.execute_script, execution_model.id)
        
        # 转换为Pydantic schema
        execution_schema = UiAutomationExecution.from_orm(execution_model)
        return UiAutomationResponse(
            success=True,
            message="执行任务创建成功",
            data=execution_schema
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/executions", response_model=UiAutomationResponse)
def get_ui_automation_executions(
    page: int = 1,
    size: int = 20,
    script_id: Optional[int] = None,
    status: Optional[str] = None,
    executed_by: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取UI自动化执行记录列表"""
    try:
        # 处理status参数：空字符串转为None，有效字符串转为枚举
        status_enum = None
        if status and status.strip():
            try:

                status_enum = ExecutionStatus(status.strip())
            except ValueError:
                # 如果状态值无效，忽略该过滤条件
                status_enum = None
        
        service = UiAutomationService(db)
        # 使用新的方法获取包含报告信息的执行记录
        result = service.get_executions_with_reports(
            page=page,
            size=size,
            script_id=script_id,
            status=status_enum,
            executed_by=executed_by
        )
        
        # 转换items中的SQLAlchemy模型为Pydantic schema
        execution_schemas = [UiAutomationExecution.from_orm(execution) for execution in result["items"]]
        result["items"] = execution_schemas
        
        return UiAutomationResponse(
            success=True,
            message="获取执行记录成功",
            data=result
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/executions/{execution_id}", response_model=UiAutomationResponse)
def get_ui_automation_execution(
    execution_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取UI自动化执行记录详情"""
    service = UiAutomationService(db)
    execution_model = service.get_execution(execution_id)
    if not execution_model:
        raise HTTPException(status_code=404, detail="执行记录不存在")
    
    # 转换为Pydantic schema
    execution_schema = UiAutomationExecution.from_orm(execution_model)
    return UiAutomationResponse(
        success=True,
        message="获取成功",
        data=execution_schema
    )


@router.post("/executions/{execution_id}/stop", response_model=UiAutomationResponse)
def stop_ui_automation_execution(
    execution_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """停止UI自动化执行"""
    # TODO: 实现停止执行逻辑
    return UiAutomationResponse(
        success=True,
        message="执行已停止"
    )


# 批量执行相关接口
@router.post("/batch-executions", response_model=UiAutomationResponse)
async def create_ui_automation_batch_execution(
    batch_data: UiAutomationBatchCreate,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建并执行批量UI自动化任务"""
    try:
        service = UiAutomationService(db)
        batch_model = await service.create_batch_execution(batch_data, current_user.id)
        
        # 在后台执行批量任务
        background_tasks.add_task(service.execute_batch, batch_model.id)
        
        # 转换为Pydantic schema
        batch_schema = UiAutomationBatch.from_orm(batch_model)
        return UiAutomationResponse(
            success=True,
            message="批量执行任务创建成功",
            data=batch_schema
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/batch-executions", response_model=UiAutomationListResponse)
def get_ui_automation_batch_executions(
    page: int = 1,
    size: int = 20,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取批量执行记录列表"""
    try:
        query = db.query(ui_automation_models.UiAutomationBatch)
        total = query.count()
        offset = (page - 1) * size
        batches = query.offset(offset).limit(size).all()
        pages = (total + size - 1) // size

        # 转换为Pydantic schema
        batch_schemas = [UiAutomationBatch.from_orm(batch) for batch in batches]
        
        return UiAutomationListResponse(
            items=batch_schemas,
            total=total,
            page=page,
            size=size,
            pages=pages
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/batch-executions/{batch_id}", response_model=UiAutomationResponse)
def get_ui_automation_batch_execution(
    batch_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取批量执行记录详情"""
    batch_model = db.query(ui_automation_models.UiAutomationBatch).filter(
        ui_automation_models.UiAutomationBatch.id == batch_id
    ).first()
    if not batch_model:
        raise HTTPException(status_code=404, detail="批量执行记录不存在")
    
    # 转换为Pydantic schema
    batch_schema = UiAutomationBatch.from_orm(batch_model)
    return UiAutomationResponse(
        success=True,
        message="获取成功",
        data=batch_schema
    )


# 统计相关接口
@router.get("/stats", response_model=UiAutomationResponse)
def get_ui_automation_stats(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取UI自动化统计信息"""
    try:
        # 脚本统计
        total_scripts = db.query(ui_automation_models.UiAutomationScript).count()
        active_scripts = db.query(ui_automation_models.UiAutomationScript).filter(
            ui_automation_models.UiAutomationScript.status == "active"
        ).count()
        
        # 执行统计
        total_executions = db.query(ui_automation_models.UiAutomationExecution).count()
        success_executions = db.query(ui_automation_models.UiAutomationExecution).filter(
            ui_automation_models.UiAutomationExecution.status == "success"
        ).count()
        
        # 今日执行统计
        from datetime import datetime, date
        today = date.today()
        today_executions = db.query(ui_automation_models.UiAutomationExecution).filter(
            ui_automation_models.UiAutomationExecution.start_time >= today
        ).count()

        stats = {
            "total_scripts": total_scripts,
            "active_scripts": active_scripts,
            "total_executions": total_executions,
            "success_executions": success_executions,
            "success_rate": round((success_executions / total_executions * 100) if total_executions > 0 else 0, 2),
            "today_executions": today_executions
        }

        return UiAutomationResponse(
            success=True,
            message="获取统计信息成功",
            data=stats
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/executions/{execution_id}/stream")
async def stream_execution_output(
    execution_id: int,
    token: str = None,
    db: Session = Depends(get_db)
):
    """SSE流式获取执行输出"""
    
    async def generate_stream():
        """生成SSE流"""
        try:
            # 验证token
            if not token:
                yield f"data: {json.dumps({'type': 'error', 'message': '缺少认证token'})}\n\n"
                return
            
            # 验证用户身份
            try:
                from ...core.security import get_current_user_from_token
                current_user = await get_current_user_from_token(token, db)
                if not current_user:
                    yield f"data: {json.dumps({'type': 'error', 'message': '认证失败'})}\n\n"
                    return
            except Exception as auth_error:
                yield f"data: {json.dumps({'type': 'error', 'message': f'认证错误: {str(auth_error)}'})}\n\n"
                return
            
            service = UiAutomationService(db)
            
            # 验证执行记录是否存在
            execution = service.get_execution(execution_id)
            if not execution:
                yield f"data: {json.dumps({'type': 'error', 'message': '执行记录不存在'})}\n\n"
                return
            
            # 发送开始信息
            yield f"data: {json.dumps({'type': 'start', 'message': f'开始流式输出执行: {execution.script.name}'})}\n\n"
            
            # 执行脚本并流式输出（从数据库读取执行选项）
            async for output_data in service.execute_script_stream(execution_id):
                yield f"data: {json.dumps(output_data)}\n\n"
                
        except Exception as e:
            yield f"data: {json.dumps({'type': 'error', 'message': f'执行失败: {str(e)}'})}\n\n"
    
    return StreamingResponse(
        generate_stream(),
        media_type="text/plain",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "text/event-stream"
        }
    )


@router.post("/executions/{execution_id}/stop", response_model=UiAutomationResponse)
async def stop_ui_automation_execution(
    execution_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """停止UI自动化执行"""
    try:
        service = UiAutomationService(db)
        
        # 获取执行记录
        execution = db.query(UiAutomationExecution).filter(
            UiAutomationExecution.id == execution_id
        ).first()
        
        if not execution:
            raise HTTPException(status_code=404, detail="执行记录不存在")
        
        # 检查执行状态
        if execution.status != ExecutionStatus.RUNNING:
            return UiAutomationResponse(
                success=False,
                message=f"执行状态为{execution.status.value}，无法停止"
            )
        
        # 停止执行
        result = await service.stop_execution(execution_id)
        
        return UiAutomationResponse(
            success=True,
            message="执行已停止",
            data=result
        )
        
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))





@router.get("/reports/view", tags=["报告管理"])
async def view_report(
    path: str
):
    """查看报告文件"""
    try:
        from fastapi.responses import FileResponse
        import os
        
        # 实例化文件服务
        ui_file_service = UiFileService()
        # 构建完整路径
        report_dir = ui_file_service.ui_test_dir / "midscene_run" / "report"
        file_path = report_dir / path
        
        # 安全检查：确保文件在允许的目录内
        if not str(file_path).startswith(str(report_dir)):
            raise HTTPException(status_code=400, detail="非法的文件路径")
        
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件不存在")
        
        # 对于HTML文件，在浏览器中预览；其他文件下载
        if file_path.suffix == ".html":
            return FileResponse(
                path=str(file_path),
                media_type="text/html"
            )
        else:
            return FileResponse(
                path=str(file_path),
                media_type="application/octet-stream",
                filename=file_path.name
            )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/reports/download", tags=["报告管理"])
async def download_report(
    path: str,
    current_user: User = Depends(get_current_user)
):
    """下载报告文件"""
    try:
        from fastapi.responses import FileResponse
        
        # 实例化文件服务
        ui_file_service = UiFileService()
        # 构建完整路径
        report_dir = ui_file_service.ui_test_dir / "midscene_run" / "report"
        file_path = report_dir / path
        
        # 安全检查：确保文件在允许的目录内
        if not str(file_path).startswith(str(report_dir)):
            raise HTTPException(status_code=400, detail="非法的文件路径")
        
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件不存在")
        
        return FileResponse(
            path=str(file_path),
            media_type="application/octet-stream",
            filename=file_path.name,
            headers={"Content-Disposition": f"attachment; filename={file_path.name}"}
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
